package com.carleasoft.mps.core.tree;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class TreeBuild {

    /**
     * 解析树形数据
     * @param topId
     * @param entityList
     * @return
     */
    public static <E extends TreeEntity<E>> List<E> getTreeList(String topId, List<E> entityList) {

       if(entityList==null || entityList.size()==0) return new ArrayList<>();

        List<E> resultList = new ArrayList<>();

        //获取顶层元素集合
        String parentId;
        for (E entity : entityList) {
            parentId = entity.getParentTargetCode();
            if(parentId == null || topId.equals(parentId) || parentId=="null" || StringUtils.isEmpty(parentId)){
                resultList.add(entity);
            }
        }

        //获取每个顶层元素的子数据集合
        for (E entity : resultList) {
            entity.setChildren(getSubList(entity.getTargetCode(), entityList));
        }
        return resultList;
    }

    /**
     * 解析树形数据
     * @param currentId
     * @param entityList
     * @return
     */
    public static <E extends TreeEntity<E>> List<E> getTreeListFromCurrent(String currentId, List<E> entityList) {

        if(entityList==null || entityList.size()==0) return new ArrayList<>();

        List<E> resultList = new ArrayList<>();

        //获取顶层元素集合
        String parentId;
        for (E entity : entityList) {
            parentId = entity.getTargetCode();
            if(currentId.equals(parentId)){
                resultList.add(entity);
            }
        }

        //获取每个顶层元素的子数据集合
        for (E entity : resultList) {
            entity.setChildren(getSubList(entity.getTargetCode(), entityList));
        }
        return resultList;
    }

    /**
     * 获取子数据集合
     * @param id
     * @param entityList
     */
    private  static  <E extends TreeEntity<E>> List<E> getSubList(String id, List<E> entityList) {
        List<E> childList = new ArrayList<>();
        String parentId;

        //子集的直接子对象
        for (E entity : entityList) {
            parentId = entity.getParentTargetCode();
            if(id.equals(parentId)){
                childList.add(entity);
            }
        }

        //子集的间接子对象
        for (E entity : childList) {
            entity.setChildren(getSubList(entity.getTargetCode(), entityList));
        }

        //递归退出条件
        if(childList.size() == 0){
            return null;
        }
        return childList;
    }
}
